package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.business.bo.HcxAppUserAddBo;
import com.ruoyi.business.bo.HcxAppUserEditBo;
import com.ruoyi.business.bo.HcxAppUserQueryBo;
import com.ruoyi.business.domain.HcxAppUser;
import com.ruoyi.business.domain.HcxMerchant;
import com.ruoyi.business.domain.HcxMerchantProduct;
import com.ruoyi.business.domain.HcxWithdrawDetail;
import com.ruoyi.business.mapper.HcxAppUserMapper;
import com.ruoyi.business.mapper.HcxMerchantMapper;
import com.ruoyi.business.mapper.HcxMerchantProductMapper;
import com.ruoyi.business.mapper.HcxWithdrawDetailMapper;
import com.ruoyi.business.service.IHcxAppUserService;
import com.ruoyi.business.vo.HcxAppUserVo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.AssertUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户Service业务层处理
 *
 * @author wsdz
 * @date 2022-08-17
 */
@Service
@AllArgsConstructor
public class HcxAppUserServiceImpl extends ServicePlusImpl<HcxAppUserMapper, HcxAppUser> implements IHcxAppUserService {

    private final RedisCache redisCache;

    private final HcxWithdrawDetailMapper withdrawDetailMapper;

    private final HcxMerchantMapper hcxMerchantMapper;

    private final HcxMerchantProductMapper hcxMerchantProductMapper;

    private final SysUserMapper sysUserMapper;

    @Override
    public HcxAppUserVo queryById(Long id) {
        return getVoById(id, HcxAppUserVo.class);
    }

    @Override
    public TableDataInfo<HcxAppUserVo> queryPageList(HcxAppUserQueryBo bo) {
        PagePlus<HcxAppUser, HcxAppUserVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), HcxAppUserVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<HcxAppUserVo> queryList(HcxAppUserQueryBo bo) {
        return listVo(buildQueryWrapper(bo), HcxAppUserVo.class);
    }

    private LambdaQueryWrapper<HcxAppUser> buildQueryWrapper(HcxAppUserQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HcxAppUser> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getUserName()), HcxAppUser::getUserName, bo.getUserName());
        lqw.like(StrUtil.isNotBlank(bo.getNickName()), HcxAppUser::getNickName, bo.getNickName());
        lqw.eq(StrUtil.isNotBlank(bo.getPhonenumber()), HcxAppUser::getPhonenumber, bo.getPhonenumber());
        lqw.eq(StrUtil.isNotBlank(bo.getSex()), HcxAppUser::getSex, bo.getSex());
        lqw.eq(StrUtil.isNotBlank(bo.getAvatar()), HcxAppUser::getAvatar, bo.getAvatar());
        lqw.eq(StrUtil.isNotBlank(bo.getPassword()), HcxAppUser::getPassword, bo.getPassword());
        lqw.eq(StrUtil.isNotBlank(bo.getPayPassword()), HcxAppUser::getPayPassword, bo.getPayPassword());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), HcxAppUser::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getInviteCode()), HcxAppUser::getInviteCode, bo.getInviteCode());
        lqw.eq(StrUtil.isNotBlank(bo.getInviteFullCode()), HcxAppUser::getInviteFullCode, bo.getInviteFullCode());
        lqw.like(StrUtil.isNotBlank(bo.getRealName()), HcxAppUser::getRealName, bo.getRealName());
        lqw.eq(StrUtil.isNotBlank(bo.getIdcard()), HcxAppUser::getIdcard, bo.getIdcard());
        lqw.eq(StrUtil.isNotBlank(bo.getIdcardImgFront()), HcxAppUser::getIdcardImgFront, bo.getIdcardImgFront());
        lqw.eq(StrUtil.isNotBlank(bo.getIdcardImgBack()), HcxAppUser::getIdcardImgBack, bo.getIdcardImgBack());
        lqw.like(StrUtil.isNotBlank(bo.getProvinceName()), HcxAppUser::getProvinceName, bo.getProvinceName());
        lqw.eq(StrUtil.isNotBlank(bo.getProvinceCode()), HcxAppUser::getProvinceCode, bo.getProvinceCode());
        lqw.like(StrUtil.isNotBlank(bo.getCityName()), HcxAppUser::getCityName, bo.getCityName());
        lqw.eq(StrUtil.isNotBlank(bo.getCityCode()), HcxAppUser::getCityCode, bo.getCityCode());
        lqw.like(StrUtil.isNotBlank(bo.getDistrictsName()), HcxAppUser::getDistrictsName, bo.getDistrictsName());
        lqw.eq(StrUtil.isNotBlank(bo.getDistrictsCode()), HcxAppUser::getDistrictsCode, bo.getDistrictsCode());
        lqw.like(StrUtil.isNotBlank(bo.getCarNum()), HcxAppUser::getCarNum, bo.getCarNum());
        lqw.eq(StrUtil.isNotBlank(bo.getAddress()), HcxAppUser::getAddress, bo.getAddress());
        lqw.eq(StrUtil.isNotBlank(bo.getUserSig()), HcxAppUser::getUserSig, bo.getUserSig());
        lqw.eq(StrUtil.isNotBlank(bo.getImId()), HcxAppUser::getImId, bo.getImId());
        lqw.eq(StrUtil.isNotBlank(bo.getOpenId()), HcxAppUser::getOpenId, bo.getOpenId());
        lqw.eq(StrUtil.isNotBlank(bo.getVipFlag()), HcxAppUser::getVipFlag, bo.getVipFlag());
        lqw.eq(StrUtil.isNotBlank(bo.getDelFlag()), HcxAppUser::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    private LambdaQueryWrapper<HcxAppUser> buildChildrenQueryWrapper(HcxAppUserQueryBo bo) {
        HcxAppUser hcxAppUser = getBaseMapper().selectById(bo.getId());
        LambdaQueryWrapper<HcxAppUser> lqw = Wrappers.lambdaQuery();
        lqw.likeRight(HcxAppUser::getInviteFullCode, hcxAppUser.getInviteFullCode() + hcxAppUser.getInviteCode());
        lqw.like(StrUtil.isNotBlank(bo.getUserName()), HcxAppUser::getUserName, bo.getUserName());
        lqw.like(StrUtil.isNotBlank(bo.getNickName()), HcxAppUser::getNickName, bo.getNickName());
        lqw.eq(StrUtil.isNotBlank(bo.getPhonenumber()), HcxAppUser::getPhonenumber, bo.getPhonenumber());
        lqw.eq(StrUtil.isNotBlank(bo.getSex()), HcxAppUser::getSex, bo.getSex());
        lqw.eq(StrUtil.isNotBlank(bo.getAvatar()), HcxAppUser::getAvatar, bo.getAvatar());
        lqw.eq(StrUtil.isNotBlank(bo.getPassword()), HcxAppUser::getPassword, bo.getPassword());
        lqw.eq(StrUtil.isNotBlank(bo.getPayPassword()), HcxAppUser::getPayPassword, bo.getPayPassword());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), HcxAppUser::getStatus, bo.getStatus());
        lqw.like(StrUtil.isNotBlank(bo.getRealName()), HcxAppUser::getRealName, bo.getRealName());
        lqw.eq(StrUtil.isNotBlank(bo.getIdcard()), HcxAppUser::getIdcard, bo.getIdcard());
        lqw.eq(StrUtil.isNotBlank(bo.getIdcardImgFront()), HcxAppUser::getIdcardImgFront, bo.getIdcardImgFront());
        lqw.eq(StrUtil.isNotBlank(bo.getIdcardImgBack()), HcxAppUser::getIdcardImgBack, bo.getIdcardImgBack());
        lqw.like(StrUtil.isNotBlank(bo.getProvinceName()), HcxAppUser::getProvinceName, bo.getProvinceName());
        lqw.eq(StrUtil.isNotBlank(bo.getProvinceCode()), HcxAppUser::getProvinceCode, bo.getProvinceCode());
        lqw.like(StrUtil.isNotBlank(bo.getCityName()), HcxAppUser::getCityName, bo.getCityName());
        lqw.eq(StrUtil.isNotBlank(bo.getCityCode()), HcxAppUser::getCityCode, bo.getCityCode());
        lqw.like(StrUtil.isNotBlank(bo.getDistrictsName()), HcxAppUser::getDistrictsName, bo.getDistrictsName());
        lqw.eq(StrUtil.isNotBlank(bo.getDistrictsCode()), HcxAppUser::getDistrictsCode, bo.getDistrictsCode());
        lqw.like(StrUtil.isNotBlank(bo.getCarNum()), HcxAppUser::getCarNum, bo.getCarNum());
        lqw.eq(StrUtil.isNotBlank(bo.getAddress()), HcxAppUser::getAddress, bo.getAddress());
        lqw.eq(StrUtil.isNotBlank(bo.getUserSig()), HcxAppUser::getUserSig, bo.getUserSig());
        lqw.eq(StrUtil.isNotBlank(bo.getImId()), HcxAppUser::getImId, bo.getImId());
        lqw.eq(StrUtil.isNotBlank(bo.getOpenId()), HcxAppUser::getOpenId, bo.getOpenId());
        lqw.eq(StrUtil.isNotBlank(bo.getVipFlag()), HcxAppUser::getVipFlag, bo.getVipFlag());
        lqw.eq(StrUtil.isNotBlank(bo.getDelFlag()), HcxAppUser::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(HcxAppUserAddBo bo) {
        HcxAppUser add = BeanUtil.toBean(bo, HcxAppUser.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(HcxAppUserEditBo bo) {
        HcxAppUser update = BeanUtil.toBean(bo, HcxAppUser.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(HcxAppUser entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }

        // 如果是商家用户 则删除商家信息
        for (Long id : ids) {
            HcxAppUser hcxAppUser = baseMapper.selectById(id);
            if(hcxAppUser.getMerchantFlag().equals("1")){
                // 查询商家
                HcxMerchant hcxMerchant = hcxMerchantMapper.selectOne(Wrappers.lambdaQuery(HcxMerchant.class).eq(HcxMerchant::getUserId, hcxAppUser.getId()));

                //删除商家上传的商品
                hcxMerchantProductMapper.delete(Wrappers.lambdaQuery(HcxMerchantProduct.class).eq(HcxMerchantProduct::getMerchantId, hcxMerchant.getId()));

                // 删除商家
                hcxMerchantMapper.delete(Wrappers.lambdaQuery(HcxMerchant.class).eq(HcxMerchant::getUserId, hcxAppUser.getId()));


                // 删除对应的后台账号
                sysUserMapper.delete(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getPhonenumber,hcxMerchant.getPersonTel()));


            }
        }
        return removeByIds(ids);
    }

    @Override
    public String importHcxAppUser(List<HcxAppUserVo> hcxAppUserList) {
        AssertUtils.isTrue(CollectionUtils.isNotEmpty(hcxAppUserList), "导入数据不能为空");
        int successNum = 0;
        for (HcxAppUserVo hcxAppUser : hcxAppUserList) {
            HcxAppUser add = BeanUtil.toBean(hcxAppUser, HcxAppUser.class);
            save(add);
            successNum++;
        }
        String msg = String.format("导入完成，共计 %d 条数据，成功 %d 条！", hcxAppUserList.size(), successNum);
        if (successNum != hcxAppUserList.size()) {
            msg = msg + String.format("失败 %d 条！", hcxAppUserList.size() - successNum);
        }
        return msg;
    }

    @Override
    public Boolean audit(HcxAppUserEditBo bo) {
        HcxAppUser hcxAppUser = new HcxAppUser();
        hcxAppUser.setId(bo.getId());
        hcxAppUser.setStatus(bo.getStatus());
        hcxAppUser.setOperOpition(bo.getOperOpition());
        boolean result = updateById(hcxAppUser);
        return result;
    }


    @Override
    public Boolean dongjie(HcxAppUserEditBo bo) {
        HcxAppUser hcxAppUser = new HcxAppUser();
        hcxAppUser.setId(bo.getId());
        hcxAppUser.setStatus(bo.getStatus());
        hcxAppUser.setDongjieOpition(bo.getOperOpition());
        boolean result = updateById(hcxAppUser);
        return result;
    }

    @Override
    public Boolean cancleDongjie(HcxAppUserEditBo bo) {
        HcxAppUser hcxAppUser = new HcxAppUser();
        hcxAppUser.setId(bo.getId());
        hcxAppUser.setStatus(bo.getStatus());
        hcxAppUser.setDongjieOpition(bo.getOperOpition());
        boolean result = updateById(hcxAppUser);
        return result;
    }

    @Override
    public TableDataInfo<HcxAppUserVo> queryAllChildrenPageList(HcxAppUserQueryBo bo) {
        PagePlus<HcxAppUser, HcxAppUserVo> result = pageVo(PageUtils.buildPagePlus(), buildChildrenQueryWrapper(bo), HcxAppUserVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public Boolean addUserPrice(HcxAppUserEditBo bo) {
        HcxAppUser hcxAppUser = getBaseMapper().selectById(bo.getId());

        String tuiguangPrice = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.TUIGUANGDANJIAN);
        AssertUtils.isNotBlank(tuiguangPrice, "请先去系统参数中设置推广奖金额");

        hcxAppUser.setSharePrice(hcxAppUser.getSharePrice().add(new BigDecimal(tuiguangPrice)).setScale(2, BigDecimal.ROUND_HALF_UP));


        boolean b = updateById(hcxAppUser);

        // 记录推广奖账单
        HcxWithdrawDetail hcxWithdrawDetail = new HcxWithdrawDetail();
        hcxWithdrawDetail.setUserId(hcxAppUser.getId());
        hcxWithdrawDetail.setRealName(hcxAppUser.getRealName());
        hcxWithdrawDetail.setDetailType(Constants.FOUR);
        hcxWithdrawDetail.setAmount(new BigDecimal(tuiguangPrice));
        hcxWithdrawDetail.setPhonenumber(hcxAppUser.getPhonenumber());
        // 谁给我贡献的(平台)
        hcxWithdrawDetail.setShareUserId(0L);
        hcxWithdrawDetail.setCreateBy("admin");
        withdrawDetailMapper.insert(hcxWithdrawDetail);

        return b;
    }
}
